#!/usr/bin/env node 
let http=require('http'),
    cp=require('child_process'),
    qs=require('querystring'),
    log=console.log
    result='';
http.createServer((req,res)=>{
  if(req.url !='/'){
    err(res);
    return;
  }
  log(req.headers);
  log('');
  switch(req.method){
    case 'GET':
      show(res);
      break;
    case 'POST':
      execCmd(req,res);
      break;
    default:
      err(res);
      break;
  }
}).listen(8080);
function show(res){
  let html=`
    <!DOCTYPE html>
    <html>
     <head>
      <meta charset='UTF-8'>
      <title>execute linux command </title>
    </head>
    <body>
    <h1>Input a Linux Command </h1>
    <from method='post' cation='/'>
          <p><input type='text' name='cmd' />
          <input type='submit' value='execute'/></p>
    </from>
    <div><pre style='font-family:Consolas;'>${result}</pre></div>
    </body>
    </html>`;
  res.statusCode=200;
  res.setHeader('Content-Type','text/html');
  res.setHeader('Content-Length',Buffer.byteLength(html));
  res.end(html);
}
function execCmd(req,res){
  let cmd='';
  req.on('data',chunk=>cmd += chunk);
  req.on('end',()=>{
    cmd=qs.parse(cmd).cmd;
    if(cmd===''){
      result = 'Please input linux command';
      show(res);
    }else{
      console.log(cmd);
      //非实时同步执行
      cp.exec(cmd,(err,stdout,stderr)=>{
        result=(err===null)? stdout : stderr;
        show(res);
      });
    }
  });
}
